# 导入json模块，用于处理JSON数据
import json

# 导入sys模块，用于访问标准输入输出
import sys

# 从typing模块导入类型注解Dict和Any
from typing import Dict, Any


# 定义一个简单的MCP服务器类
class SimpleMCPServer:
    # 构造函数，初始化服务器
    def __init__(self):
        # 定义服务器支持的工具列表
        self.tools = {
            # 工具1：读取文件
            "read_file": {
                # 工具描述
                "description": "读取指定文件的内容",
                # 工具参数定义
                "parameters": {
                    "type": "object",
                    "properties": {
                        # 参数file_path，类型为字符串
                        "file_path": {
                            "type": "string",
                            "description": "要读取的文件路径",
                        }
                    },
                    # 必需参数
                    "required": ["file_path"],
                },
            },
            # 工具2：获取天气
            "get_weather": {
                # 工具描述
                "description": "获取指定城市的天气信息",
                # 工具参数定义
                "parameters": {
                    "type": "object",
                    "properties": {
                        # 参数city，类型为字符串
                        "city": {"type": "string", "description": "城市名称"}
                    },
                    # 必需参数
                    "required": ["city"],
                },
            },
        }

    # 处理客户端请求的方法
    def handle_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
        # 获取请求的方法名
        method = request.get("method")
        # 获取请求参数，默认为空字典
        params = request.get("params", {})

        # 如果请求方法为tools/list
        if method == "tools/list":
            # 返回服务器支持的工具列表
            return {
                "jsonrpc": "2.0",
                "id": request.get("id"),
                "result": {"tools": list(self.tools.values())},
            }

        # 如果请求方法为tools/call
        elif method == "tools/call":
            # 获取要调用的工具名称
            tool_name = params.get("name")
            # 获取工具调用参数
            tool_args = params.get("arguments", {})

            # 如果调用read_file工具
            if tool_name == "read_file":
                return self._read_file(tool_args, request.get("id"))
            # 如果调用get_weather工具
            elif tool_name == "get_weather":
                return self._get_weather(tool_args, request.get("id"))
            # 如果工具不存在
            else:
                return {
                    "jsonrpc": "2.0",
                    "id": request.get("id"),
                    "error": {
                        "code": -32601,
                        "message": f"Method {tool_name} not found",
                    },
                }

        # 如果请求方法未知
        else:
            # 返回方法未找到的错误
            return {
                "jsonrpc": "2.0",
                "id": request.get("id"),
                "error": {"code": -32601, "message": f"Method {method} not found"},
            }

    # 读取文件的私有方法
    def _read_file(self, args: Dict[str, Any], request_id: Any) -> Dict[str, Any]:
        # 获取文件路径参数
        file_path = args.get("file_path")
        try:
            # 打开文件并读取内容
            with open(file_path, "r", encoding="utf-8") as f:
                content = f.read()
            # 返回读取成功的结果
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "content": [
                        {
                            "type": "text",
                            "text": f"文件 {file_path} 的内容：\n{content}",
                        }
                    ]
                },
            }
        # 捕获异常，返回错误信息
        except Exception as e:
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32000, "message": f"读取文件失败：{str(e)}"},
            }

    # 获取天气信息的私有方法
    def _get_weather(self, args: Dict[str, Any], request_id: Any) -> Dict[str, Any]:
        # 获取城市参数，默认为北京
        city = args.get("city", "北京")
        # 定义模拟天气数据
        weather_data = {
            "北京": {"temperature": "25°C", "condition": "晴"},
            "上海": {"temperature": "28°C", "condition": "多云"},
            "广州": {"temperature": "30°C", "condition": "雨"},
        }

        # 获取指定城市的天气数据，若无则返回默认值
        weather = weather_data.get(city, {"temperature": "20°C", "condition": "未知"})

        # 返回天气信息
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "content": [
                    {
                        "type": "text",
                        "text": f"{city}的天气：{weather['condition']}，温度{weather['temperature']}",
                    }
                ]
            },
        }


# 主程序入口
if __name__ == "__main__":
    # 创建服务器实例
    server = SimpleMCPServer()

    # 从标准输入循环读取每一行请求
    for line in sys.stdin:
        try:
            # 解析JSON请求
            request = json.loads(line.strip())
            # 处理请求，获取响应
            response = server.handle_request(request)
            # 输出响应到标准输出
            print(json.dumps(response, ensure_ascii=False))
            # 刷新标准输出缓冲区
            sys.stdout.flush()
        # 捕获JSON解析错误
        except json.JSONDecodeError:
            # 输出解析错误响应
            print(
                json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "id": None,
                        "error": {"code": -32700, "message": "Parse error"},
                    },
                    ensure_ascii=False,
                )
            )
            # 刷新标准输出缓冲区
            sys.stdout.flush()
